package com.zweirm.lagee_quizing_web.controller;

import com.zweirm.lagee_quizing_web.domain.*;
import com.zweirm.lagee_quizing_web.service.PaperService;
import com.zweirm.lagee_quizing_web.service.QuestionService;
import com.zweirm.lagee_quizing_web.service.QuizService;
import com.zweirm.lagee_quizing_web.service.ResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@Controller
public class QuizController {
    @Autowired
    private QuizService quizService;

    @Autowired
    private ResultService resultService;

    @Autowired
    private PaperService paperService;

    @RequestMapping("/myQuiz")
    public String myQuiz(Model model) {
        List<Quiz> quizzes = quizService.findQuizByClazz();
        model.addAttribute("quizzes", quizzes);
        return "/myQuiz";
    }

    @RequestMapping("/quiz/{quizId}")
    public String takeQuiz(@PathVariable Long quizId, Model model) {
        Result result = resultService.findResultByUserIdAndQuiz(quizId);
        if (result != null) {
            return showResult(model, quizId, result);
        } else {
            return takeQuizWithoutResult(model, quizId);
        }
    }

    private String showResult(Model model, Long quizId, Result result) {
        // 获取当前考试
        Quiz quiz = quizService.findQuizById(quizId);
        model.addAttribute("quiz_id", quizId);
        model.addAttribute("quiz_title", quiz.getTitle());
        model.addAttribute("quiz_type", quiz.getType());

        // 获取考试对应的试卷
        Paper paper = paperService.findPaperById(quiz.getPaper().getId());
        model.addAttribute("paper_name", paper.getName());
        model.addAttribute("paper_description", paper.getDescription());

        // 传递考试结果信息
        String passRate = result.getPassRate();
        model.addAttribute("passRate", passRate);
        Double passRatePercentDouble = Double.parseDouble(passRate);
        if (passRatePercentDouble == 1.0) {
            model.addAttribute("passRatePercent", "100%");
        } else {
            model.addAttribute("passRatePercent", passRate.substring(2) + "%");
        }
        return "forward:/showResultWithResult";
    }

    private String takeQuizWithoutResult(Model model, Long quizId) {
        // 获取当前考试
        Quiz quiz = quizService.findQuizById(quizId);
        model.addAttribute("quiz_id", quizId);
        model.addAttribute("quiz_title", quiz.getTitle());
        model.addAttribute("quiz_type", quiz.getType());

        // 获取考试对应的试卷
        Paper paper = paperService.findPaperById(quiz.getPaper().getId());
        model.addAttribute("paper_name", paper.getName());
        model.addAttribute("paper_description", paper.getDescription());

        // 获取试卷对应的试题
        List<Question> questions = paper.getQuestions();
        model.addAttribute("questions", questions);

        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);

            // 获取试题对应的选项
            List<Choice> choices = question.getChoices();
            model.addAttribute("question" + i + "choices", choices);
        }
        return "forward:/takeQuiz";
    }

    @RequestMapping("/judge")
    public String doJudge(HttpServletRequest request, Model model) {
        // 试题总数量和试卷ID
        String questionSize = request.getParameter("questionSize");
        String quizId = request.getParameter("quizId");

        // 通过试卷ID获取试卷
        Quiz quiz = quizService.findQuizById(Long.valueOf(quizId));
        Paper paper = paperService.findPaperById(quiz.getPaper().getId());

        // 获取试卷对应的试题
        List<Question> questions = paper.getQuestions();

        int countForRight = 0;

        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            int answer = -1;

            // 获取试题对应的选项
            List<Choice> choices = question.getChoices();
            model.addAttribute("question" + i + "choices", choices);

            for (int j = 0; j < choices.size(); j++) {
                Choice choice = choices.get(j);
                Boolean isRight = choice.getRight();
                if (isRight) {
                    answer = j + 1;
                }
            }

            // 判断用户是否选对
            String userAnswer = request.getParameter("answer_" + i + "_radio");
            if (Integer.parseInt(userAnswer) == answer) {
                countForRight++;
                model.addAttribute("question" + i + "false", true);
            } else {
                model.addAttribute("question" + i + "false", false);
            }
        }

        // 计算通过率
        BigDecimal count = new BigDecimal(countForRight);
        BigDecimal questionAmount = new BigDecimal(questionSize);
        BigDecimal passRate = count.divide(questionAmount, 2, BigDecimal.ROUND_HALF_UP);

        // 将考试结果存入数据库
        resultService.saveResult(passRate.toString(), quiz);

        // 将必要信息带给结果页面
        model.addAttribute("quiz_id", quizId);
        model.addAttribute("quiz_title", quiz.getTitle());
        model.addAttribute("quiz_type", quiz.getType());
        model.addAttribute("paper_name", paper.getName());
        model.addAttribute("paper_description", paper.getDescription());
        model.addAttribute("questions", questions);
        model.addAttribute("passRate", passRate.toString());

        // 传输百分比通过率
        Double passRatePercentDouble = Double.parseDouble(passRate.toString());
        if (passRatePercentDouble == 1.0) {
            model.addAttribute("passRatePercent", "100%");
        } else {
            model.addAttribute("passRatePercent", passRate.toString().substring(2) + "%");
        }

        return "/showResult";
    }
}
